﻿/*
 * Copyright (c) 2015-2016 Constantijn Evenhuis (blueprints@const.nl)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
using Blueprints.IO;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace Blueprints.Xml
{
    /// <summary>
    /// A blueprint reader that reads xml.
    /// </summary>
    public sealed class XmlBlueprintReader : IBlueprintReader
    {
        private readonly XmlReader reader;
        private readonly Stream stream;
        private readonly Queue<INode> pending = new Queue<INode>();

        /// <summary>
        /// Creates a new XmlBlueprintReader.
        /// </summary>
        /// <param name="stream">The stream to read from.</param>
        /// <param name="documentUri">The uri of the blueprint being read.</param>
        public XmlBlueprintReader(Stream stream, Uri documentUri)
        {
            XmlReaderSettings settings = new XmlReaderSettings()
            {
                IgnoreProcessingInstructions = true,
                IgnoreWhitespace = true,
            };

            this.stream = stream;
            reader = XmlReader.Create(stream, settings);
            DocumentUri = documentUri;
        }

        /// <summary>
        /// Gets the uri of the blueprint being read.
        /// </summary>
        public Uri DocumentUri
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the current node.
        /// </summary>
        public INode Current
        {
            get;
            private set;
        }

        object IEnumerator.Current
        {
            get { return Current; }
        }

        /// <summary>
        /// Moves to the next node.
        /// </summary>
        /// <returns>True if a next node was found, false if at the end of the document.</returns>
        public bool MoveNext()
        {
            if (pending.Count > 0)
            {
                Current = pending.Dequeue();
                return true;
            }

            while (reader.Read())
            {
                INode node;
                if (EnqueueCurrentNode(out node))
                {
                    Current = node;
                    return true;
                }
            }

            Current = default(INode);
            return false;
        }

        void IEnumerator.Reset()
        {
            throw new NotSupportedException();
        }

        void IDisposable.Dispose()
        {
            pending.Clear();
            Current = null;
            reader.Dispose();
        }

        private bool EnqueueCurrentNode(out INode node)
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    node = GetCurrentNodeAsStartNode();
                    return true;
                case XmlNodeType.Text:
                    node = GetCurrentNodeAsContent(true);
                    return true;
                case XmlNodeType.CDATA:
                    node = GetCurrentNodeAsContent(false);
                    return true;
                case XmlNodeType.EndElement:
                    node = GetCurrentNodeAsEndNode();
                    return true;
                case XmlNodeType.Comment:
                    node = GetCurrentNodeAsCommentNode();
                    return true;
            }

            node = default(INode);
            return false;
        }

        private StartNode GetCurrentNodeAsStartNode()
        {
            string id = null;
            string type = null;
            string link = null;
            if (reader.MoveToFirstAttribute())
            {
                do
                {
                    if (reader.NamespaceURI.Equals(XmlBlueprintWriter.BlueprintNamespace, StringComparison.Ordinal))
                    {
                        if (reader.LocalName.Equals("type", StringComparison.Ordinal))
                        {
                            type = reader.Value;
                        }
                        else if (reader.LocalName.Equals("link", StringComparison.Ordinal))
                        {
                            link = reader.Value;
                        }
                        else if (reader.LocalName.Equals("id", StringComparison.Ordinal))
                        {
                            id = reader.Value;
                        }
                    }
                    else if (!string.IsNullOrEmpty(reader.Prefix))
                    {
                        continue;
                    }
                    else if (reader.Name.Equals("id", StringComparison.Ordinal))
                    {
                        id = reader.Value;
                    }
                    else
                    {
                        pending.Enqueue(new StartNode(reader.LocalName, null, null, null));
                        pending.Enqueue(new ContentNode(reader.Value));
                        pending.Enqueue(new EndNode());
                    }
                }
                while (reader.MoveToNextAttribute());
            }

            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                pending.Enqueue(new EndNode());
            }

            return new StartNode(reader.LocalName, type, id, link);
        }

        private ContentNode GetCurrentNodeAsContent(bool trim)
        {
            string content = reader.Value;
            if (trim)
            {
                content = content.Trim();
            }

            return new ContentNode(content);
        }

        private EndNode GetCurrentNodeAsEndNode()
        {
            return new EndNode();
        }

        private CommentNode GetCurrentNodeAsCommentNode()
        {
            return new CommentNode(reader.Value);
        }
    }
}